package com.andaily.service.operation.instance;

import com.andaily.domain.application.ApplicationInstance;
import com.andaily.domain.application.ApplicationInstanceRepository;
import com.andaily.domain.shared.BeanProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Shengzhao Li
 */
public class ApplicationInstanceDeleter {

    private static final Logger LOGGER = LoggerFactory.getLogger(ApplicationInstanceDeleter.class);
    private transient ApplicationInstanceRepository instanceRepository = BeanProvider.getBean(ApplicationInstanceRepository.class);
    private String guid;

    public ApplicationInstanceDeleter(String guid) {
        this.guid = guid;
    }

    public boolean delete() {
        final ApplicationInstance instance = instanceRepository.findByGuid(guid, ApplicationInstance.class);
        if (instance.enabled()) {
            LOGGER.debug("Forbid delete enabled ApplicationInstance[guid={}]", instance.guid());
            return false;
        }

        instanceRepository.deleteInstanceFrequencyMonitorLogs(guid);
        instanceRepository.delete(instance);
        LOGGER.debug("Delete ApplicationInstance[guid={}] and FrequencyMonitorLogs", instance.guid());
        return true;
    }
}